import axios, { InternalAxiosRequestConfig, AxiosResponse, FormData, AxiosProgressEvent, AxiosError } from '@ohos/axios'

import { getToken } from '../store'
import { globalCfg } from '../../config/setting'
import { Log } from '../utils/log'
import errorCode from './errorCode'
import { popMsg } from './ruoyi';

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: globalCfg.baseUrl,
  // 超时
  timeout: 60000,
  headers: {
    'Content-Type': 'multipart/form-data'
  },
});
// request拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    Log.info("调用axios，请求后台服务地址：", config.baseURL + config.url)
    // 是否需要设置 token
    const isToken = (config.headers || {})['isToken'] === false;
    Log.info("调用axios，是否设置token：",!isToken)
    Log.info("调用axios，获取缓存token")
    let token = getToken()
    Log.info("调用axios，获取缓存token成功：", token)
    if (token && !isToken && config.headers) {
      config.headers['Authorization'] = 'Bearer ' + token; // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config;
  },
  (error: AxiosError) => {
    Log.error("拦截request系统错误", error);
    Promise.reject(error);
  }
);
// 响应拦截器
service.interceptors.response.use(
  (res: AxiosResponse) => {
    Log.info("调用axios，返回成功：", res.status)
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    Log.info("调用axios，服务端返回状态码：", code)
    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' || res.request.responseType === 'array_buffer') {
      Log.info("调用axios，返回二进制数据")
      return res.data;
    }
    let data = typeof res.data === 'object' ? JSON.stringify(res.data) : res.data;
    Log.info('请求后台返回数据：', data)
    if (code === 200) {
      //正常返回
      return Promise.resolve(res.data);
    } else {
      // 返回错误获取错误信息
      const msg = errorCode[code] || res.data.msg || errorCode['default'];
      Log.info("调用axios，返回错误信息：", msg)
      popMsg(msg)
      return Promise.reject(new Error(msg));
    }
  },
  (error: AxiosError) => {
    let { message } = error;
    Log.error('拦截response系统错误', message, error.code);
    if (message === AxiosError.ERR_NETWORK) {
      message = '后端接口连接异常';
    } else if (message === AxiosError.ETIMEDOUT) {
      message = '系统接口请求超时';
    }
    popMsg(message)
    return Promise.reject(error);
  }
);
//通用上传方法
export function upload(name: string, fileName: string, buf: ArrayBuffer, url: string, context: any, isToken: boolean, callback?: Function) {
  let headers = { 'isToken': isToken }
  let formData = new FormData()
  formData.append(name, buf, fileName);
  Log.info('上传地址', url)
  // 发送请求
  return service.post<string, any, FormData>(url, formData, {
    headers: headers,
    context: context,
    onUploadProgress: (progressEvent: AxiosProgressEvent): void => {
      //Log.info("上传进度: " + progressEvent && progressEvent.loaded && progressEvent.total ? Math.ceil(progressEvent.loaded / progressEvent.total * 100) + '%' : '0%');
      callback(progressEvent)
    },
  })
}